package tk1.uebung05.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.Timestamp;
import java.util.Date;

public class ServerNTPThread extends Thread {

	private Socket client;
	private final long offset = 10000;
	

	public ServerNTPThread(Socket client) {
		this.client = client;
	}

	public void run() {
	    int count = 0;
		while (count < 10) {
			try {
				long requestTime = readMessage(client);
				writeResponse(client, requestTime);
				count++;
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
    private long readMessage(java.net.Socket socket) throws IOException {
        BufferedReader bufferedReader = 
            new BufferedReader(
                new InputStreamReader(
                    socket.getInputStream()));
        char[] buffer = new char[200];
        int numberOfChars = bufferedReader.read(buffer, 0, 200); // blockiert bis Nachricht empfangen
        String timeAsString = new String(buffer, 0, numberOfChars);
        Long time = Long.valueOf(timeAsString);
        return time.longValue();
    }
    
    private void writeResponse(java.net.Socket socket, long requestTime) throws IOException {
    	long ti_3 = requestTime;
    	
    	long ti_2 = (new Timestamp((new Date()).getTime())).getTime();
    	ti_2 = ti_2 + offset;
    	
    	try {
			sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    	
    	long ti_1 = (new Timestamp((new Date()).getTime())).getTime();
    	ti_1 = ti_1 + offset;
    	
    	String response = String.valueOf(ti_3) + "," + String.valueOf(ti_2) + "," + String.valueOf(ti_1);   	
        PrintWriter printWriter =
            new PrintWriter(
                new OutputStreamWriter(
                    socket.getOutputStream()));
        long transmissionDelay = (long)((Math.random() * 90) + 10);
    	try {
			sleep(transmissionDelay);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        printWriter.print(response);
        printWriter.flush();
    }
}
